package com.mooc.lib_video.ui.home_video

import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.mooc.ijk.widget.IJKView
import com.mooc.lib_common.action.BusAction
import com.mooc.lib_common.action.BusConst
import com.mooc.lib_common.arouter.service.UserLoginAService
import com.mooc.lib_common.model.FeedEntity
import com.mooc.lib_common.mvvm.BaseFragment
import com.mooc.lib_video.R
import com.mooc.lib_video.adapter.HomeVideoAdapter
import com.mooc.lib_video.databinding.FragmentVideoBinding
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class VideoFragment:BaseFragment<VideoViewModel,FragmentVideoBinding>(),OnItemChildClickListener {

    var rv : RecyclerView?=null
    override fun initView() {
        rv = v.root.findViewById(R.id.video_rv)
        rv!!.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                //newState->对应recyclerview3个常量值用来帮助我们监听recyclerview滑动状态
                //RecyclerView.SCROLL_STATE_IDLE->静止状态
                //RecyclerView.SCROLL_STATE_SETTLING->用户抛动recyclerview列表
                //RecyclerView.SCROLL_STATE_DRAGGING->用户拖拽滑动
                //使用状态判断进行视频播放
                if (newState == RecyclerView.SCROLL_STATE_IDLE){
                    //获取当前列表中recyclerview顶部item索引
                    val manager : LinearLayoutManager = recyclerView.layoutManager as LinearLayoutManager
//                    manager.findFirstVisibleItemPosition()
//                    manager.findFirstCompletelyVisibleItemPosition()
                    //异同:都是获取列表中最顶部item索引；findFirstVisibleItemPosition->无论最上一条是否显示完整都返回item索引
                    //findFirstCompletelyVisibleItemPosition->获取最上面完整显示的item索引
                    val position = manager.findFirstCompletelyVisibleItemPosition()
                    val adapter : HomeVideoAdapter = rv!!.adapter as HomeVideoAdapter
                    //由于当前item为多布局->先区分布局->如果为ImageView不处理->VideoView处理
                    //由于当前item为多布局模式->专门用来先视频布局;专门用来显示图片的布局
                    //getItemViewType==2->视频item类型->全部在播放视频暂停播放
                    //从而保证当前列表中最上一条完整展示的视频view可以播放->唯一播放
                    //减小内存消耗，处理掉同时播放视频混音问题
                    if (adapter.getItemViewType(position) == 2) {
                        var index = 0
                        //暂停列表中全部IJKVideoView
                        while (index < adapter.itemCount) {
                            if (adapter.getItemViewType(index) == 2) {
                                var view = adapter.getViewByPosition(index, R.id.list_player_view)
                                if (view!=null) {
                                    var ijkView: IJKView = view as IJKView
                                    if (ijkView.isPlay())
                                        ijkView.relase()
                                }
                            }
                            index++
                        }
                        //根据列表中最上一条展示的item索引获取视频item中的ijkview
                        var ijkView: IJKView =
                            adapter.getViewByPosition(position, R.id.list_player_view) as IJKView
                        //设置播放
                        ijkView.setPath(adapter.data[position].url!!)
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //获取recyclerview在X轴或Y轴偏移->用户滑动
                //从下向上滑动dy为正->手指上一次的点-当前点 Y值
                //从上向下滑动dy为负
                //滑动吸顶
            }

        })
        val manager = LinearLayoutManager(context)
        manager.orientation = LinearLayoutManager.VERTICAL
        rv!!.layoutManager = manager
        val adapter = HomeVideoAdapter()
        adapter.setOnItemChildClickListener(this)
        rv!!.adapter = adapter
    }

    override fun bindLayout(): Int {
        return R.layout.fragment_video
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun initData() {
        EventBus.getDefault().register(this)
        vm.videoData.observe(this,{
            val adapter : HomeVideoAdapter = rv!!.adapter as HomeVideoAdapter
            adapter.setNewInstance(it.data!!)
        })
        vm.requestFeed()
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val homeVideoAdapter : HomeVideoAdapter = adapter as HomeVideoAdapter
        val entity : FeedEntity = homeVideoAdapter.getItem(position)
        val isLogin : Boolean = (ARouter.getInstance().build("/lib_user/UserLoginService").
        navigation() as UserLoginAService).isLogin()
        if (!isLogin){
            ARouter.getInstance().build("/lib_user/LoginActivity").
            navigation()
            return
        }
        ARouter.getInstance().build("/lib_video/DetailActivity")
            .withParcelable("item",entity).
            navigation()
    }
    lateinit var bean : FeedEntity

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshLogin(action: BusAction){
        //登录返回->data处理掉从那个item子控件监听跳转的
        if (action.equals(BusConst.LOGINACTION)){
            ARouter.getInstance().build("/lib_video/DetailActivity")
                .withParcelable("item",bean).
                navigation()
        }
    }

}